import { history } from 'umi';

let token: string = JSON.parse(sessionStorage.getItem('user'))?.token || '';

let extraRoutes: any[]; // 定义额外路由变量
// 动态新增路由  配置文件 根据权限来更新路由
export function patchRoutes({ routes }: any) {
  // console.log(routes, 'router');
  routes.unshift({
    path: '/foo',
    component: require('@/pages/foo/index').default,
  });
  //   合并服务端返回的路由
  extraRoutes.map((item) => {
    routes.unshift({
      path: item.path,
      component: require(`${item.component}`).default,
    });
  });
}

// 先执行  复写render
export function render(oldRender: any) {
  //   模拟从服务端获得的路由
  extraRoutes = [{ path: '/server', component: './pages/home/index.tsx' }];
  // 做一些权限校验 l路由拦截
  if (location.pathname === '/friend') {
    if (!token) {
      history.push('/login');
    }
  }
  oldRender();
}

interface Client {
  matchedRoutes: any;
  location?: number; // ？表示可选属性
  routes: any;
  action: string; //只读，只能在创建时赋值
}

//  监听路由的改变 埋点 比如用于设置标题，
export function onRouteChange({
  matchedRoutes,
  location,
  routes,
  action,
}: Client) {
  if (matchedRoutes.length) {
    document.title = matchedRoutes[matchedRoutes.length - 1].route.title || '';
  }
}
